/**
 * @ClassName: BaseDao
 * @Description: 鎴愰兘鍟嗕細妤风爜OA寮�彂baseDao瀹炵幇
 * @author 绉︽湁榫�
 * @date 2012-9-12 涓嬪崍5:57:36
 *
 */
package com.yc.eduonline.common;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
 
@SuppressWarnings({ "unchecked", "rawtypes" })
public class BaseDao<T, ID extends Serializable> implements IBaseDao<T, ID> {
	//public Logger logger = Logger.getLogger(this.getClass());
	private SessionFactory sessionFactory;
	protected Class<T> entityClass;

	public BaseDao() {

	}

	protected Class getEntityClass() {
		if (entityClass == null) {
			entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
			//logger.debug("T class = " + entityClass.getName());
		}
		return entityClass;
	}

	@Override
	public void save(T t) throws DataAccessException {
		this.getSession().save(t);
	}
	
	@Override
	public void saveOrUpdate(T t) throws DataAccessException {
		this.getSession().saveOrUpdate(t);
	}

	@Override
	public T load(ID id) throws DataAccessException {
		T load = (T) this.getSession().load(getEntityClass(), id);
		return load;
	}

	@Override
	public T get(ID id) throws DataAccessException {
		T load = (T) this.getSession().get(getEntityClass(), id);
		return load;
	}

	@Override
	public boolean contains(T t) throws DataAccessException {
		return this.getSession().contains(t);
	}

	@Override
	public void delete(T t) throws DataAccessException {
		this.getSession().delete(t);
	}

	@Override
	public void deleteAll(Collection<T> entities) throws DataAccessException {
		for(Object entity : entities) {
			this.getSession().delete(entity);
		}
	}

	@Override
	public List<T> loadByHQL(String hqlString)throws DataAccessException {
		return this.getSession().createQuery(hqlString).list();
	}

	@Override
	public List<T> loadBySQL(String sqlString) throws DataAccessException {
		return this.getSession().createSQLQuery(sqlString).list();
	}

	@Override
	public void refresh(T t) throws DataAccessException {
		this.getSession().refresh(t);
	}

	@Override
	public void update(T t) throws DataAccessException {
		this.getSession().update(t);
	}
	
	/**
	 * @return the sessionFactory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * @param sessionFactory the sessionFactory to set
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
}
